/*-----------------------------------------------------------------------------
	The contents of this file are subject to the Mozilla Public License
	Version 1.1 (the "License"); you may not use this file except in
	compliance with the License.You may obtain a copy of the License at
	http://www.mozilla.org/MPL/MPL-1.1.html
	
	Software distributed under the License is distributed on an "AS IS"
	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	License for the specific language governing rights and limitations
	under the License.
	
	The Original Code is Fever Framework code.
	
	The Initial Developer of the Original Code is Romain Ecarnot.
	Portions created by Initial Developer are Copyright (C) 2006
	the Initial Developer. All Rights Reserved.
	
	Contributor(s):
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-----------------------------------------------------------------------------*/

import fever.data.crypt.ICrypter;

/**
 * <strong>TEA</strong> string encryption.
 * 
 * <p>Orignal ActionScript 2.0 implementation by Mika Palmu in his 
 * AsCrypt library, available in http://www.meychi.com/
 * 
 * @author Mika Palmu
 * @author Romain Ecarnot
 */
class fever.data.crypt.TEA implements ICrypter
{	
	//-------------------------------------------------------------------------
	// Private properties
	//-------------------------------------------------------------------------
	
	private static var _instance : ICrypter;
	
		
	//-------------------------------------------------------------------------
	// Public API
	//-------------------------------------------------------------------------
	
	/**
	 * Returns the TEA crypter.
	 */
	public static function getProcess() : ICrypter
	{
		if( !_instance ) _instance = new TEA();
		return _instance;	
	}
	
	/**
	 * Encrypts a string with the specified key.
	 */
	public function encrypt( value , key : String ) : String
	{
		var v:Array = charsToLongs(strToChars( value.toString() ) );
		var k:Array = charsToLongs(strToChars(key));
		var n:Number = v.length;
		if (n == 0) return "";
		if (n == 1) v[n++] = 0;
		var z:Number = v[n-1], y:Number = v[0], delta:Number = 0x9E3779B9;
		var mx:Number, e:Number, q:Number = Math.floor(6+52/n), sum:Number = 0;
		while (q-- > 0) {
			sum += delta;
			e = sum>>>2 & 3;
			var p : Number;
			for (p = 0; p<n-1; p++) {
				y = v[p+1];
				mx = (z>>>5^y<<2)+(y>>>3^z<<4)^(sum^y)+(k[p&3^e]^z);
				z = v[p] += mx;
			}
			y = v[0];
			mx = (z>>>5^y<<2)+(y>>>3^z<<4)^(sum^y)+(k[p&3^e]^z);
			z = v[n-1] += mx;
		}
		return charsToHex(longsToChars(v));
	}

	/**
	 * Decrypts a string with the specified key.
	 */
	public function decrypt( value, key : String ) : String
	{
		var v:Array = charsToLongs(hexToChars( value.toString() ));
		var k:Array = charsToLongs(strToChars(key));
		var n:Number = v.length;
		if (n == 0) return "";
		var z:Number = v[n-1], y:Number = v[0], delta:Number = 0x9E3779B9;
		var q : Number = Math.floor(6 + 52/n);
		var mx:Number, e:Number, sum:Number = q*delta;
		while (sum != 0) {
			e = sum>>>2 & 3;
			var p : Number;
			for(p = n-1; p > 0; p--){
				z = v[p-1];
				mx = (z>>>5^y<<2)+(y>>>3^z<<4)^(sum^y)+(k[p&3^e]^z);
				y = v[p] -= mx;
			}
			z = v[n-1];
			mx = (z>>>5^y<<2)+(y>>>3^z<<4)^(sum^y)+(k[p&3^e]^z);
			y = v[0] -= mx;
			sum -= delta;
		}
		return charsToStr(longsToChars(v));
	}
	
	
	//-------------------------------------------------------------------------
	// Private implementation
	//-------------------------------------------------------------------------
	
	/**
	 * Constructor.
	 */
	private function TEA()
	{
		
	}
	
	private function charsToLongs(chars:Array):Array
	{
		var temp:Array = new Array(Math.ceil(chars.length/4));
		for (var i:Number = 0; i<temp.length; i++) {
			temp[i] = chars[i*4] + (chars[i*4+1]<<8) + (chars[i*4+2]<<16) + (chars[i*4+3]<<24);
		}
		return temp;
	}
	private function longsToChars(longs:Array):Array
	{
		var codes:Array = new Array();
		for (var i:Number = 0; i<longs.length; i++) {
			codes.push(longs[i] & 0xFF, longs[i]>>>8 & 0xFF, longs[i]>>>16 & 0xFF, longs[i]>>>24 & 0xFF);
		}
		return codes;
	}
	private function charsToHex(chars:Array):String
	{
		var result:String = new String("");
		var hexes:Array = new Array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
		for (var i:Number = 0; i<chars.length; i++) {
			result += hexes[chars[i] >> 4] + hexes[chars[i] & 0xf];
		}
		return result;
	}
	private function hexToChars(hex:String):Array
	{
		var codes:Array = new Array();
		for (var i:Number = (hex.substr(0, 2) == "0x") ? 2 : 0; i<hex.length; i+=2) {
			codes.push(parseInt(hex.substr(i, 2), 16));
		}
		return codes;
	}
	private function charsToStr(chars:Array):String
	{
		var result:String = new String("");
		for (var i:Number = 0; i<chars.length; i++) {
			result += String.fromCharCode(chars[i]);
		}
		return result;
	}
	private function strToChars(str:String):Array
	{
		var codes:Array = new Array();
		for (var i:Number = 0; i<str.length; i++) {
			codes.push(str.charCodeAt(i));
		}
		return codes;
	}
	
}